package logic

import (
	"context"
	"fmt"
	"housing/model/mysql"
	"housing/model/redis"
	"housing/pkg"

	"housing/housingrpc/housingrpc"
	"housing/housingrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatepasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatepasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatepasswordLogic {
	return &UpdatepasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatepasswordLogic) Updatepassword(in *housingrpc.UpdatepasswordRequest) (*housingrpc.UpdatepasswordResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Captachaupdate" + in.Phone)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("图形验证码不正确，请重新输入")
	}
	cmd := redis.Client.Get("sendSmsupdate" + in.Phone)
	if cmd.Val() != in.Sendsms {
		return nil, fmt.Errorf("短信验证码不正确，请从新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("phone =?", in.Phone).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号未被注册，请前往注册")
	}
	if user.Password != pkg.Md5Password(in.Oldpassword) {
		return nil, fmt.Errorf("旧密码输入不正确，请重新输入")
	}
	if in.Password != in.Newpassword {
		return nil, fmt.Errorf("确认密码输入不正确，请重新输入")
	}
	if user.Password == in.Password {
		return nil, fmt.Errorf("新旧密码不能一致，请重新输入")
	}
	user.Password = pkg.Md5Password(in.Password)
	mysql.DB.Debug().Updates(&user)
	redis.Client.Del("Captachaupdate" + in.Phone)
	redis.Client.Del("sendSmsupdate" + in.Phone)
	return &housingrpc.UpdatepasswordResponse{Id: int64(user.ID)}, nil
}
